package com.fuint.framework.pagination;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.PageRequest;

import java.util.List;

/**
 * 分页助手类，用于替换PageHelper
 *
 * Created by FSQ
 * CopyRight https://www.fuint.cn
 */
public class PaginationHelper {

    /**
     * 创建MyBatis-Plus分页对象
     *
     * @param currentPage 当前页码
     * @param pageSize 每页大小
     * @return Page对象
     */
    public static <T> Page<T> createPage(int currentPage, int pageSize) {
        return new Page<>(currentPage, pageSize);
    }

    /**
     * 将MyBatis-Plus分页结果转换为PaginationResponse
     *
     * @param page MyBatis-Plus分页结果
     * @param clz 数据类型
     * @return PaginationResponse
     */
    public static <T> PaginationResponse<T> convertToPaginationResponse(IPage<T> page, Class<? extends T> clz) {
        PageRequest pageRequest = PageRequest.of((int) page.getCurrent() - 1, (int) page.getSize());
        PageImpl<T> pageImpl = new PageImpl<>(page.getRecords(), pageRequest, page.getTotal());
        
        PaginationResponse<T> paginationResponse = new PaginationResponse<>(pageImpl, clz);
        paginationResponse.setTotalPages((int) page.getPages());
        paginationResponse.setTotalElements(page.getTotal());
        paginationResponse.setContent(page.getRecords());
        
        return paginationResponse;
    }

    /**
     * 将自定义数据列表转换为PaginationResponse
     *
     * @param dataList 数据列表
     * @param currentPage 当前页码
     * @param pageSize 每页大小
     * @param total 总记录数
     * @param clz 数据类型
     * @return PaginationResponse
     */
    public static <T> PaginationResponse<T> convertToPaginationResponse(List<T> dataList, int currentPage, int pageSize, long total, Class<? extends T> clz) {
        PageRequest pageRequest = PageRequest.of(currentPage - 1, pageSize);
        PageImpl<T> pageImpl = new PageImpl<>(dataList, pageRequest, total);
        
        PaginationResponse<T> paginationResponse = new PaginationResponse<>(pageImpl, clz);
        paginationResponse.setTotalPages((int) Math.ceil((double) total / pageSize));
        paginationResponse.setTotalElements(total);
        paginationResponse.setContent(dataList);
        
        return paginationResponse;
    }
}
